package com.muyun.data.modeler.infrastructure.general.toolkit;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.muyun.data.modeler.infrastructure.general.consts.MessageConsts;
import com.muyun.data.modeler.infrastructure.general.exceptions.TipException;

import java.io.IOException;

/**
 * Jackson ObjectMapper工具类
 *
 * @author muyun12
 * @date 2020-12-20 11:04:26
 * @since 0.1.0
 */
public class ObjectMapperToolkit {

    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    static {
        OBJECT_MAPPER.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
    }

    private ObjectMapperToolkit() {
        throw new TipException(MessageConsts.CAN_NOT_INSTANCE_CLASS);
    }

    /**
     * 忽略未知属性反序列化JSON字符串
     * 
     * @param content
     * @param valueType
     * @return
     * @throws IOException
     */
    public static <T> T readValue(String content, Class<T> valueType) throws IOException {
        return OBJECT_MAPPER.readValue(content, valueType);
    }

    /**
     * 把指定的对象序列化为JSON字符串
     *
     * @param value
     * @return
     * @throws JsonProcessingException
     */
    public static String writeValue(Object value) throws JsonProcessingException {
        return OBJECT_MAPPER.writeValueAsString(value);
    }
}
